/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.shop.web.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import co.yixiang.annotation.AnonymousAccess;
import co.yixiang.aop.log.Log;
import co.yixiang.common.api.ApiResult;
import co.yixiang.common.web.controller.BaseController;
import co.yixiang.enums.AppFromEnum;
import co.yixiang.enums.ProductEnum;
import co.yixiang.exception.ErrorRequestException;
import co.yixiang.modules.shop.entity.YxSales;
import co.yixiang.modules.shop.entity.YxStoreProduct;
import co.yixiang.modules.shop.service.*;
import co.yixiang.modules.shop.service.impl.YxSystemConfigServiceImpl;
import co.yixiang.modules.shop.web.dto.ProductDTO;
import co.yixiang.modules.shop.web.param.YxStoreProductQueryParam;
import co.yixiang.modules.shop.web.param.YxStoreProductRelationQueryParam;
import co.yixiang.modules.shop.web.vo.*;
import co.yixiang.modules.user.entity.YxSystemAttachment;
import co.yixiang.modules.user.service.YxSystemAttachmentService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.web.vo.YxUserQueryVo;
import co.yixiang.utils.OrderUtil;
import co.yixiang.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * <p>
 * 商品控制器
 * </p>
 *
 * @author hupeng
 * @since 2019-10-19
 */
@Slf4j
@RestController
@Api(value = "产品模块", tags = "投资端:产品模块", description = "产品模块")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StoreProductController extends BaseController {

    private final YxStoreProductService storeProductService;
    private final YxStoreProductRelationService productRelationService;
    private final YxSystemConfigService yxSystemConfigServiceImpl;
    private final YxSalesService yxSalesService;
    private final YxInvestCartService yxInvestCartService;
    private final YxSystemConfigService yxSystemConfigService;
    private final YxStoreProductAttrService yxStoreProductAttrService;


    @Value("${file.path}")
    private String path;


    /**
     * 获取首页更多产品
     */
    @AnonymousAccess
    @GetMapping("/products")
    @ApiOperation(value = "商品列表", notes = "商品列表")
    public ApiResult<List<YxStoreProductQueryVo>> goodsList(YxStoreProductQueryParam productQueryParam) {
        return ApiResult.ok(storeProductService.getGoodsList(productQueryParam));
    }

    @GetMapping("/product/saleRanking")
    @ApiOperation(value = "销售量排行榜", notes = "销售量排行榜")
    public ApiResult<List<YxStoreProductQueryVo>> saleRanking(YxStoreProductQueryParam productQueryParam) {
        return ApiResult.ok(storeProductService.saleRanking(productQueryParam));
    }


    /**
     * 普通商品详情
     */
    @Log(value = "查看商品详情", type = 1)
    @GetMapping("/product/detail/{id}")
    @ApiOperation(value = "普通商品详情", notes = "普通商品详情")
    public ApiResult<ProductDTO> detail(@PathVariable Integer id,
                                        @RequestParam(value = "", required = false) String latitude,
                                        @RequestParam(value = "", required = false) String longitude,
                                        @RequestParam(value = "", required = false) String from) {
        int uid = SecurityUtils.getUserId().intValue();
        ProductDTO productDTO = storeProductService.goodsDetail(id, 0, uid, latitude, longitude);
        //添加浏览记录
        YxStoreProductRelationQueryParam yxStoreProductRelationQueryParam = new YxStoreProductRelationQueryParam();
        yxStoreProductRelationQueryParam.setId(id);
        yxStoreProductRelationQueryParam.setCategory("product");
        productRelationService.addRroductRelation(yxStoreProductRelationQueryParam, uid, "browse");

        return ApiResult.ok(productDTO);
    }

    /**
     * 普通商品详情
     */
    @Log(value = "认购商品分析")
    @GetMapping("/product/analysis/{id}")
    @ApiOperation(value = "认购商品分析", notes = "认购商品分析")
    public ApiResult<YxStoreProductAnalysisVo> analysis(@PathVariable Integer id
    ) {
        int uid = SecurityUtils.getUserId().intValue();
        YxStoreProductAnalysisVo yxStoreProductAnalysisVo = new YxStoreProductAnalysisVo();
        List<YxStoreProductSalesVo> yxStoreProductSalesList = new ArrayList<>();
        List<YxStoreProductSalesVo> jdSalesList = new ArrayList<>();
        List<YxStoreProductSalesVo> tmSalesList = new ArrayList<>();
        List<YxStoreProductSalesVo> snSalesList = new ArrayList<>();

        for (int i = 15; i > 0; i--) {
            YxStoreProductSalesVo yxStoreProductSalesVo = new YxStoreProductSalesVo();
            yxStoreProductSalesVo.setSalesCount("" + (int) (Math.random() * 200 + 180));
            SimpleDateFormat df = new SimpleDateFormat("MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            yxStoreProductSalesVo.setSalesDate(df.format(calendar.getTime()));
            yxStoreProductSalesList.add(yxStoreProductSalesVo);
        }

        for (int i = 15; i > 0; i--) {
            YxStoreProductSalesVo yxStoreProductSalesVo = new YxStoreProductSalesVo();
            yxStoreProductSalesVo.setSalesCount("" + (int) (Math.random() * 100 + 130));
            SimpleDateFormat df = new SimpleDateFormat("MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            yxStoreProductSalesVo.setSalesDate(df.format(calendar.getTime()));
            jdSalesList.add(yxStoreProductSalesVo);
        }

        for (int i = 15; i > 0; i--) {
            YxStoreProductSalesVo yxStoreProductSalesVo = new YxStoreProductSalesVo();
            yxStoreProductSalesVo.setSalesCount("" + (int) (Math.random() * 100 + 120));
            SimpleDateFormat df = new SimpleDateFormat("MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            yxStoreProductSalesVo.setSalesDate(df.format(calendar.getTime()));
            tmSalesList.add(yxStoreProductSalesVo);
        }
        for (int i = 15; i > 0; i--) {
            YxStoreProductSalesVo yxStoreProductSalesVo = new YxStoreProductSalesVo();
            yxStoreProductSalesVo.setSalesCount("" + (int) (Math.random() * 100 + 110));
            SimpleDateFormat df = new SimpleDateFormat("MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            yxStoreProductSalesVo.setSalesDate(df.format(calendar.getTime()));
            snSalesList.add(yxStoreProductSalesVo);
        }


        yxStoreProductAnalysisVo.setYxStoreProductSalesList(yxStoreProductSalesList);
        yxStoreProductAnalysisVo.setJdSalesList(jdSalesList);
        yxStoreProductAnalysisVo.setTmSalesList(tmSalesList);
        yxStoreProductAnalysisVo.setSnSalesList(snSalesList);

        yxStoreProductAnalysisVo.setAreaScore("" + (int) (Math.random() * 31 + 70));
        yxStoreProductAnalysisVo.setBrandScore("" + (int) (Math.random() * 31 + 70));
        yxStoreProductAnalysisVo.setPlatformScore("" + (int) (Math.random() * 31 + 70));
        yxStoreProductAnalysisVo.setLikeScore("" + (int) (Math.random() * 31 + 70));
        yxStoreProductAnalysisVo.setSeasonScore("" + (int) (Math.random() * 31 + 70));
        yxStoreProductAnalysisVo.setRiskScore("" + (int) (Math.random() * 31 + 20));
        yxStoreProductAnalysisVo.setCompositeScore("" + (int) (Math.random() * 31 + 70));

        //商品信息
        yxStoreProductAnalysisVo.setYxStoreProduct(storeProductService.getYxStoreProductById(id));
        yxStoreProductAnalysisVo.setProperty("季节性,地域性,偏好性,品牌性");
        Map<String, Object> returnMap = yxStoreProductAttrService.getProductAttrDetail(id, 0, 0);
        List<YxStoreProductAttrQueryVo> attrList = (List<YxStoreProductAttrQueryVo>)returnMap.get("productAttr");
        if(attrList != null && attrList.size() > 0){
            yxStoreProductAnalysisVo.setSuk(attrList.get(0).getAttrValues());
        }
        //添加浏览记录
        YxStoreProductRelationQueryParam yxStoreProductRelationQueryParam = new YxStoreProductRelationQueryParam();
        yxStoreProductRelationQueryParam.setId(id);
        yxStoreProductRelationQueryParam.setCategory("product");
        productRelationService.addRroductRelation(yxStoreProductRelationQueryParam, uid, "browse");
        return ApiResult.ok(yxStoreProductAnalysisVo);
    }


    /**
     * 认购商品购物车系统保留操作
     */
    @Log(value = "认购商品购物车系统保留操作", type = 1)
    @GetMapping("/product/cartLock/{cartId}")
    @ApiOperation(value = "认购商品购物车系统保留操作", notes = "认购商品购物车系统保留操作")
    public ApiResult<String> productCartLock(@PathVariable String cartId) {
        int uid = SecurityUtils.getUserId().intValue();
        Map<String, Object> cartGroup = yxInvestCartService.getUserProductCartList(uid, cartId, 1);
        List<YxInvestCartQueryVo> cartInfo = (List<YxInvestCartQueryVo>) cartGroup.get("valid");
        for (YxInvestCartQueryVo storeCart : cartInfo) {
            //查询保留商品
            YxStoreProduct product = storeProductService.getById(storeCart.getProductId());
            if (product.getLockStatus() != null && product.getLockStatus() == 1 && product.getLockerId() != uid) {
                return ApiResult.fail("商品：" + product.getStoreName() + "正在被认购中");
            }
        }
        for (YxInvestCartQueryVo storeCart : cartInfo) {

            YxStoreProduct yxStoreProduct = storeProductService.getById(storeCart.getProductId());
            yxStoreProduct.setLockStatus(1);
            yxStoreProduct.setLockTime(new Date());
            yxStoreProduct.setLockType(2);
            String investProductLockTimeOut = yxSystemConfigService.getData("invest_product_lock");
            yxStoreProduct.setLockReleaseTime(Integer.parseInt(investProductLockTimeOut) * 60);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.SECOND, Integer.parseInt(investProductLockTimeOut) * 360);
            yxStoreProduct.setLockReleaseDateTime(calendar.getTime());
            yxStoreProduct.setLocker(yxSalesService.getById(uid).getRealName());
            yxStoreProduct.setLockerId(uid);
            storeProductService.updateById(yxStoreProduct);


        }
        return ApiResult.ok("success");
    }


    /**
     * 保留商品列表
     */
    @Log(value = "保留商品操作", type = 1)
    @PostMapping("/product/lock/{id}")
    @ApiOperation(value = "保留商品操作", notes = "保留商品操作")
    public ApiResult<Object> productLock(@PathVariable Integer id) {
        int uid = SecurityUtils.getUserId().intValue();
        YxSales yxSales = yxSalesService.getById(uid);
        //1.普通业务员   2.经理   3集团员工  4总监
        int productLockMaxCount = 0;
        if (yxSales.getGroupId() == 1) {
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_sales"));
        } else if (yxSales.getGroupId() == 2) {
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_handle"));
        } else if (yxSales.getGroupId() == 3) {
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_group"));
        } else if (yxSales.getGroupId() == 4) {
            productLockMaxCount = Integer.parseInt(yxSystemConfigService.getData("product_lock_times_manager"));
        }
        //商品实际保留数量
        YxStoreProductQueryParam productQueryParam = new YxStoreProductQueryParam();
        if (storeProductService.getLockProductCount(productQueryParam, uid) >= productLockMaxCount) {
            return ApiResult.fail("您保留的商品已达指标");
        }

        YxStoreProduct yxStoreProduct = storeProductService.getById(id);
        if (yxStoreProduct == null) {
            return ApiResult.fail("该商品不存在");
        }
        if (yxStoreProduct.getLockStatus() != null && yxStoreProduct.getLockStatus() == 1) {
            return ApiResult.fail("该商品已被其他人锁定");

        }


        yxStoreProduct.setLockStatus(1);
        yxStoreProduct.setLockTime(new Date());
        yxStoreProduct.setLockType(1);
        String handleLockTimeOut = yxSystemConfigServiceImpl.getData("handle_lock");
        yxStoreProduct.setLockReleaseTime(Integer.parseInt(handleLockTimeOut) * 3600);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, Integer.parseInt(handleLockTimeOut) * 360);
        yxStoreProduct.setLockReleaseDateTime(calendar.getTime());
        yxStoreProduct.setLocker(yxSalesService.getById(uid).getRealName());
        yxStoreProduct.setLockerId(uid);
        storeProductService.updateById(yxStoreProduct);
        return ApiResult.ok("success");
    }

    /**
     * 释放保留商品操作
     */
    @Log(value = "释放保留商品操作", type = 1)
    @PostMapping("/product/lockRelease/{id}")
    @ApiOperation(value = "释放保留商品操作", notes = "释放保留商品操作")
    public ApiResult<Object> productLockRelease(@PathVariable Integer id) {
        //查询商品保留状态
        YxStoreProduct yxStoreProduct = storeProductService.getById(id);
        if(yxStoreProduct.getLockStatus() == 0){
            return ApiResult.fail("该商品没有被保留");
        }
        yxStoreProduct.setLockStatus(0);
        storeProductService.updateById(yxStoreProduct);
        return ApiResult.ok("success");
    }


    /**
     * 添加收藏
     */
    @Log(value = "添加收藏", type = 1)
    @PostMapping("/collect/add")
    @ApiOperation(value = "添加收藏", notes = "添加收藏")
    public ApiResult<Object> collectAdd(@Validated @RequestBody YxStoreProductRelationQueryParam param) {
        int uid = SecurityUtils.getUserId().intValue();
        productRelationService.addRroductRelation(param, uid, "collect");
        return ApiResult.ok("success");
    }

    /**
     * 取消收藏
     */
    @Log(value = "取消收藏", type = 1)
    @PostMapping("/collect/del")
    @ApiOperation(value = "取消收藏", notes = "取消收藏")
    public ApiResult<Object> collectDel(@Validated @RequestBody YxStoreProductRelationQueryParam param) {
        int uid = SecurityUtils.getUserId().intValue();
        productRelationService.delRroductRelation(param, uid, "collect");
        return ApiResult.ok("success");
    }


}

